from py3db.mysql import MySql
from config.db import DB_CONFIG, DB_COLUMN_TYPE, REDIS_CONFIG
from config.app import APP_CODE
from app.get_app_info import AppData
from framework.translate import Translate
from redis import Redis


class DbFrame:
    def __init__(self, database="mysql", config={}):
        self.db_config = DB_CONFIG if not config else dict(DB_CONFIG, **config)
        self.db = MySql(DB_CONFIG['host'], DB_CONFIG['user'], DB_CONFIG['password'], database)
        return self

    @classmethod
    def clear_redis_url(cls, app_code):
        redis = Redis(host=REDIS_CONFIG['host'], port=REDIS_CONFIG['port'])
        redis.delete(app_code)

    @classmethod
    def create_database(cls, db_name, *args, **kwargs):
        frame = cls.__init__(cls, *args, **kwargs)
        frame.db.operation_database(f"CREATE DATABASE {db_name}")

    @classmethod
    def drop_database(cls, db_name, *args, **kwargs):
        frame = cls.__init__(cls, *args, **kwargs)
        frame.db.operation_database(f"DROP DATABASE {db_name}")

    @classmethod
    def create_all_table(cls, app_code):
        temp1, temp2, field_info = AppData().get_one_info(app_code)
        item_dict = {}
        for field in field_info:
            if field[1] == 'list':
                continue
            if not len(item_dict) or not item_dict.get(field[6]):
                item_dict[field[6]] = [field]
            elif item_dict.get(field[6]):
                item_dict[field[6]].append(field)
        for key, value in item_dict.items():
            cls.create_one_table(key, value, app_code)

    @classmethod
    def create_one_table(cls, table_name, table_columns_list=[], app_code="", *args, **kwargs):
        translate = Translate()
        frame = cls.__init__(cls, database=app_code, *args, **kwargs)
        no_length_type = ("text", "mediumtext")
        table_generate_list = ["id int auto_increment primary key comment '编号'"]
        for table_column in table_columns_list:
            column_name = translate.get_english_word(table_column[1]).result
            column_type = DB_COLUMN_TYPE.get("mysql")[table_column[3]]
            column_type = column_type + f"({table_column[4]})" if column_type not in no_length_type else column_type
            column_list = [
                column_name,
                column_type,
                "null",
                "comment",
                f"'{table_column[1]}'"
            ]
            column_str = "\t\t\t" + " ".join(column_list)
            table_generate_list.append(column_str)

        table_main_str = ",\n".join(table_generate_list)
        table_sql = f"""
        create table `{table_name}`
        (
            {table_main_str},
            next_url varchar(200) null comment '下一链接',
            next_layout_id int null comment '下一版面编号',
            createtime timestamp    default CURRENT_TIMESTAMP not null,
            updatetime timestamp    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
        );
        """
        # print(table_sql)
        frame.db.operation_database(table_sql)


def frame_run():
    DbFrame.clear_redis_url(APP_CODE)
    DbFrame.drop_database(APP_CODE)
    DbFrame.create_database(APP_CODE)
    DbFrame.create_all_table(APP_CODE)


if __name__ == '__main__':
    frame_run()
